package com.mindskip.xzs.listener;
//该代码段是一个事件监听器，在收到CalculateExamPaperAnswerCompleteEvent事件时，会将事件中的信息存储到数据库中。
//1. 获取当前时间
//2. 从事件中获取试卷答案信息：试卷、试卷答案、试题客户答案列表
//3. 将试卷答案存储到数据库
//4. 对于需要存储为文本内容的答案，先存储为文本内容对象，再将其ID关联到试题客户答案中
//5. 将试题客户答案关联到对应的试卷答案中
//6. 根据试卷类型的不同，处理不同的逻辑：如果试卷类型是任务类型，则存储考试客户答案信息到数据库中
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.enums.ExamPaperTypeEnum;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.event.CalculateExamPaperAnswerCompleteEvent;
import com.mindskip.xzs.service.ExamPaperAnswerService;
import com.mindskip.xzs.service.TaskExamCustomerAnswerService;
import com.mindskip.xzs.service.TextContentService;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Component
public class CalculateExamPaperAnswerListener implements ApplicationListener<CalculateExamPaperAnswerCompleteEvent> {

    private ExamPaperAnswerService examPaperAnswerService = null;

    private TextContentService textContentService = null;
    private TaskExamCustomerAnswerService examCustomerAnswerService = null;

  

    @Override
    /**
     * 监听CalculateExamPaperAnswerCompleteEvent事件，将事件中的信息存储到数据库
     * @param calculateExamPaperAnswerCompleteEvent CalculateExamPaperAnswerCompleteEvent事件对象
     */
    @Transactional
    public void onApplicationEvent(CalculateExamPaperAnswerCompleteEvent calculateExamPaperAnswerCompleteEvent) {
        // 获取当前时间
        Date now = new Date();

        // 从事件中获取试卷答案信息
        ExamPaperAnswerInfo examPaperAnswerInfo = (ExamPaperAnswerInfo) calculateExamPaperAnswerCompleteEvent.getSource();
        ExamPaper examPaper = examPaperAnswerInfo.getExamPaper();
        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers = examPaperAnswerInfo.getExamPaperQuestionCustomerAnswers();

        // 将试卷答案存储到数据库
        examPaperAnswerService.insertByFilter(examPaperAnswer);

        // 对于需要存储为文本内容的答案，先存储为文本内容对象，再将其ID关联到试题客户答案中
        examPaperQuestionCustomerAnswers.stream().filter(a -> QuestionTypeEnum.needSaveTextContent(a.getQuestionType())).forEach(d -> {
            TextContent textContent = new TextContent(d.getAnswer(), now);
            textContentService.insertByFilter(textContent);
            d.setTextContentId(textContent.getId());
            d.setAnswer(null);
        });



        // 根据试卷类型的不同，处理不同的逻辑
        switch (ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
            case Task: {
                // 如果试卷类型是任务类型，则存储考试客户答案信息到数据库中
                examCustomerAnswerService.insertOrUpdate(examPaper, examPaperAnswer, now);
                break;
            }
            default:
                break;
        }
    }
}

